package com.imay.live.activity.user;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.imay.base.helper.NetworkHelper;
import com.imay.capturefilter.utils.ICUtils;
import com.imay.dialog.Dialoger;
import com.imay.live.activity.user.util.NameLengthFilter;
import com.imay.live.activity.user.util.NickFilter;
import com.imay.live.analytics.MobclickAgent;
import com.imay.live.helper.CallBack;
import com.imay.live.helper.DialogFragmentHelper;
import com.imay.live.helper.MediaHelper;
import com.imay.live.helper.PreferenceHelper;
import com.imay.live.manager.AccountManager;
import com.imay.live.manager.SensitiveWordFilterManager;
import com.imay.live.manager.UploadFileManager;
import com.imay.live.proto.ErrorResult;
import com.imay.live.proto.ResultCode;
import com.imay.live.proto.account.AccountCheckNameResp;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.utils.ToastUtil;
import com.imay.live.R;
import com.yalantis.ucrop.UCrop;

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.imay.dialog.Dialoger.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE;
import static com.imay.dialog.Dialoger.SYS_IMAGE_ACTIVITY_REQUEST_CODE;
import static com.imay.live.proto.ResultCode.CodeSuccess;

/**
 * 用户信息
 * Created by chan on 2017/4/1.
 */
public class InformationActivity extends UserBaseActivity implements View.OnClickListener {

    private String checkNickRequest = "";

    private TextView mRegisterSure;
    private ImageView mIvInf;

    private String imagePath;
    private String resultUrl;
    private EditText mEtNick;

    private Context mContext;

    public static void startActivity(Activity activity, int i, long phone, long sms, String secret) {
        Intent intent = new Intent(activity, InformationActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt("phoneCountry", i);
        bundle.putLong("phone", phone);
        bundle.putLong("verifyCode", sms);
        bundle.putString("secret", secret);
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    public static void startActivityForResult(Activity activity, int i, long phone, long sms, String secret, int requestCode) {
        Intent intent = new Intent(activity, InformationActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt("phoneCountry", i);
        bundle.putLong("phone", phone);
        bundle.putLong("verifyCode", sms);
        bundle.putString("secret", secret);
        intent.putExtras(bundle);
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_user_information;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mContext = this;

        setTitle(getString(R.string.str_register_title));

        mRegisterSure = $(R.id.tv_register_sure);
        mRegisterSure.setOnClickListener(this);

        mEtNick = $(R.id.tv_register_nickname);
        mEtNick.addTextChangedListener(textWatcher);
        NickFilter nickFilter = new NickFilter();
        NameLengthFilter filter = new NameLengthFilter(16);
        InputFilter[] filters = new InputFilter[]{filter, nickFilter};
        mEtNick.setFilters(filters);

        mIvInf = $(R.id.iv_inf_img);
        mIvInf.setOnClickListener(this);
    }

    final TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void afterTextChanged(Editable s) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
            if (TextUtils.isEmpty(s)) {
                mRegisterSure.setBackground(getResources().getDrawable(R.drawable.shape_corner100_bc));
                mRegisterSure.setClickable(false);
                return;
            } else {
                String string = s.toString();
                stringFilter(string);
                if (TextUtils.isEmpty(string)) {
                    mRegisterSure.setBackground(getResources().getDrawable(R.drawable.shape_corner100_9e));
                    mRegisterSure.setClickable(false);
                } else {
                    mRegisterSure.setBackground(getResources().getDrawable(R.drawable.shape_corner100_9e));
                    mRegisterSure.setClickable(true);
                }
                return;
            }
        }
    };

    public static String stringFilter(String str) {
        String regEx = "[#@\n\t]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("");
    }

    /**
     * 检查昵称是否重复
     */
    private void checkNickName(String s1) {
        DialogFragmentHelper.showLoadingDialog(getSupportFragmentManager(), getString(R.string.str_register_loading));
        checkNickRequest = ProtoRequestHelper.task(ProtoHttpFactory.checkNick(s1)).setTag(this.hashCode()).request(InformationActivity.this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_register_sure:
                if (!NetworkHelper.getInstance().hasConnection()) {
                    DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
                    ErrorResult.toastError(mContext, ResultCode.CodeNetErrorAction);
                    return;
                }
                if (TextUtils.isEmpty(resultUrl)) {
                    ToastUtil.show(mContext, mContext.getString(R.string.str_upload_note));
                    break;
                }
                if (!SensitiveWordFilterManager.getInstance().hasSensitiveWord(mEtNick)) {
                    checkNickName(mEtNick.getText().toString());
                } else {
                    ToastUtil.show(mContext, R.string.sensitive_nickname);
                }
                break;
            case R.id.iv_inf_img:
                MediaHelper.showMediaSheet(this);
                break;
        }
    }

    // 上传头像
    private void upload() {
        UploadFileManager.getInstance().uploadHead(imagePath, new UploadFileManager.UploadCallBack() {
            @Override
            public void uploadSuccess(String fileUrl) {
                ToastUtil.show(mContext, getString(R.string.str_upload_success));
                resultUrl = fileUrl;
            }

            @Override
            public void uploadFailer(int errorCode, String errorMessage) {
                ToastUtil.show(mContext, getString(R.string.str_upload_failer));
            }
        });
    }

    @Override
    public void onRequestSuccess(String command, String data) {
        if (checkNickRequest.equals(command)) {
            AccountCheckNameResp resp = JSON.parseObject(data, AccountCheckNameResp.class);
            if (resp.result == CodeSuccess) {
                mRegisterSure.setBackground(getResources().getDrawable(R.drawable.shape_corner100_9e));
                mRegisterSure.setClickable(true);
                registerUser();
            } else {
                ErrorResult.toastError(mContext, resp.result);
                mRegisterSure.setBackground(getResources().getDrawable(R.drawable.shape_corner100_bc));
                mRegisterSure.setClickable(false);
            }
        }
    }

    @Override
    public void onRequestError(String command, int code, String message) {
        DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
        ErrorResult.toastError(mContext, code);
        if (checkNickRequest.equals(command)) {
            mRegisterSure.setBackground(getResources().getDrawable(R.drawable.shape_corner100_bc));
            mRegisterSure.setClickable(false);
        }
    }

    private void registerUser() {
        Editable nickStr = mEtNick.getText();
        if (TextUtils.isEmpty(nickStr)) {
            return;
        }
        String s1 = nickStr.toString();
        final Intent intent = getIntent();
        final int phoneCountry = intent.getIntExtra("phoneCountry", 86);
        final long phone = intent.getLongExtra("phone", -1);
        final long verifyCode = intent.getLongExtra("verifyCode", -1);
        final String secret = intent.getStringExtra("secret");
        AccountManager.getInstance().registerPhone(phoneCountry, phone, Long.toString(verifyCode), secret, s1, resultUrl, new CallBack() {
            @Override
            public void onSuccess() {
                DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
                ToastUtil.showImg(mContext, getString(R.string.str_register_success), R.mipmap.jiaohutishidagou_3x, 200);
                //SuggestActivity.startActivity(mContext);
                //MainActivity2.startActivity(InformationActivity.this, getIntent().getStringExtra(H5Helper.H5REDIRECTION_KEY));
                //ActivityHelper.getInstance().finishActivity(ResigterActivity.class);
                PreferenceHelper.getInstance().saveUserInf(phoneCountry, phone + "", secret);
                setResult(RESULT_OK);
                finish();
            }

            @Override
            public void onError(int code, String message) {
                DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
                if (code == ResultCode.CodeAccountPhoneRegisted) {
                    AccountManager.getInstance().loginByPasswordHttp(phoneCountry, phone, secret, this);
                } else {
                    ToastUtil.showImg(mContext, ErrorResult.getString(mContext, code), R.mipmap.jiaohutishidaxia_3x, 200);
                }
            }
        });
    }

    @Override
    protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
        switch (requestCode) {
            case SYS_IMAGE_ACTIVITY_REQUEST_CODE:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        Uri uri = data.getData();
                        String path = Dialoger.getPath(InformationActivity.this, uri);
                        if (TextUtils.isEmpty(path)) {
                            ToastUtil.show(mContext, R.string.str_img_error);
                            return;
                        }
                        File file = ICUtils.getOutputMediaFile(InformationActivity.this);
                        UCrop.Options options = new UCrop.Options();
                        options.setToolbarColor(Color.BLACK);
                        options.setActiveWidgetColor(Color.BLACK);
                        options.setStatusBarColor(Color.BLACK);
                        options.setHideBottomControls(true);
                        UCrop.of(Uri.fromFile(new File(path)), Uri.fromFile(file))
                                .withOptions(options)
                                .withAspectRatio(9, 9)
                                .withMaxResultSize(300, 300)
                                .start(InformationActivity.this);
                    } else {
                        ToastUtil.show(mContext, R.string.str_img_error);
                    }
                }
                break;
            case CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE:
                if (RESULT_OK == resultCode) {
                    if (data != null) {
                        File file = ICUtils.getOutputMediaFile(InformationActivity.this);
                        String path = data.getStringExtra("path");
                        if (TextUtils.isEmpty(path)) {
                            ToastUtil.show(mContext, R.string.str_img_error);
                            return;
                        }
                        UCrop.Options options = new UCrop.Options();
                        options.setToolbarColor(Color.BLACK);
                        options.setActiveWidgetColor(Color.BLACK);
                        options.setStatusBarColor(Color.BLACK);
                        options.setHideBottomControls(true);
                        UCrop.of(Uri.fromFile(new File(path)), Uri.fromFile(file))
                                .withOptions(options)
                                .withAspectRatio(9, 9)
                                .withMaxResultSize(300, 300)
                                .start(InformationActivity.this);
                    } else {
                        ToastUtil.show(mContext, R.string.str_img_error);
                    }
                }
                break;
            case UCrop.REQUEST_CROP:
                if (RESULT_OK == resultCode) {
                    final Uri resultUri = UCrop.getOutput(data);
                    if (resultUri != null) {
                        imagePath = Dialoger.getPath(InformationActivity.this, resultUri);
                        mIvInf.setImageBitmap(BitmapFactory.decodeFile(imagePath));
                        upload();
                    }
                    break;
                }
            default:
                super.onActivityResult(requestCode, resultCode, data);
                break;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }
}
